package com.example.pay.rest;


import cn.hutool.core.util.RandomUtil;
import com.union.pay.ccb.bean.req.CcbPayReq;
import com.union.pay.ccb.bean.vo.CcbWxJsapiResult;
import com.union.pay.ccb.enums.TradeTypeEnum;
import com.union.pay.ccb.service.CcbPayService;
import com.example.pay.utils.IpUtils;
import com.google.common.collect.Maps;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;


@Slf4j
@RestController
@RequiredArgsConstructor
public class PayRest {
    private final CcbPayService ccbPayService;

    @GetMapping("test")
    public String test() {
        String orderNo = System.currentTimeMillis() + RandomUtil.randomNumbers(17);
        CcbWxJsapiResult result = ccbPayService.purchase(CcbPayReq.builder()
                        .orderId(orderNo)
                .clientIp(IpUtils.getHostIp())
                .payment("0.01")
                .openId("oEQJvuApazBCJYv6z13JuVZD4wRs")
                .tradeType(TradeTypeEnum.JSAPI.name())
                .build());
        System.out.println(result);
        return "ok";
    }


    /**
     * 建行支付结果通知
     *
     * @param request
     * @return
     */
    @PostMapping("/callBackCcb")
    public String callBackCcb(HttpServletRequest request) {
        log.debug("callBackCCB start!");
        Map<String, String> map = Maps.newHashMap();
        Enumeration<String> parameterNames = request.getParameterNames();
        StringBuilder data = new StringBuilder();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            String value = request.getParameter(name);
            map.put(name, value);
            data.append(name).append("=").append(value).append("&");
        }
        if(log.isDebugEnabled()) {
            log.debug("request 回调信息=====》{} {}", data, map);
        }
        return null;
    }
}
